<?php
namespace app\api\controller;

class InsuranceRefundPlan extends Permission
{
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 1500;
        $map = [];

        if( isset($this->input_data['plate_number']) && $this->input_data['plate_number'] != '' ) $map['plate_number'] = $this->input_data['plate_number'];

        if( isset($this->input_data['status']) && $this->input_data['status'] != 99999999 ) $map['a.status'] = $this->input_data['status'];

        if( isset($this->input_data['insurance']) ) $map['b.insurance'] = ['LIKE','%'.$this->input_data['insurance'].'%'];

        if( isset($this->input_data['deadline']) && $this->input_data['deadline'] != '全部')
        {
            $map['plan_date'] = $this->input_data['deadline'] == '已过期' ? $map['plan_date'] = ['<',date('Y-m-d')] : $map['plan_date'] = ['>=',date('Y-m-d')];
        }
        if($this->post('area_id') > 0)
        {
            $map['area_id'] = $this->post('area_id');
        }
        else
        {
            $map['area_id'] = ['IN',$this->myAllAreaIds];
        }


        $total = db('InsuranceRefundPlan')->alias('a')->join('insurance b','a.insurance_id = b.id','LEFT')->join('vehicle c','b.vehicle_id = c.id','LEFT')->where($map)->count();
        $rows = db('InsuranceRefundPlan')->alias('a')->join('insurance b','a.insurance_id = b.id','LEFT')->join('vehicle c','b.vehicle_id = c.id','LEFT')->field('a.*,b.insurance,b.cate,b.insurance_salesman,b.refund_amount,b.refund_rebate,b.refund_pdf,b.refund_date,c.plate_number')->order('id DESC')->order('plan_date ASC,id ASC')->page($page,$limit)->where($map)->select();

        
        $list = [];
        foreach ($rows as $v) {

            $v['day'] = timeToDay(strtotime($v['plan_date']));
            $v['create_time'] = date('Y-m-d H:i',$v['create_time']);
            $v['abort_time'] = date('Y-m-d H:i',$v['abort_time']);
            $v = $this->_getStatus($v);

            $list[] = $v;
        }
        
        $data = [
            'total' => $total,
            'list' => $list,
            'sql' => db()->getLastSql()
        ];
        $this->resSuc($data);
    }

    private function _getStatus($v)
    {
        $text = [];
        $text[0] = '待处理';
        $text[20] = '已退保';
        $text[30] = '已取消';

        $type = [];
        $type[0] = 'info';
        $type[20] = 'success';
        $type[30] = 'danger';

        $v['statusText'] = $text[$v['status']];
        $v['statusType'] = $type[$v['status']];

        return $v;
    }

    public function del()
    {
        $data = [
            'id' => $this->input_data['id'],
            'status' => 30,
            'abort_user' => $this->user['realname'],
            'abort_user_id' => $this->user['id'],
            'abort_time' => time(),
        ];
        db('InsuranceRefundPlan')->update( $data );
        
        $this->resSuc('ok');
    }

    public function update()
    {
        if(strtotime($this->input_data['plan_date']) < time()) $this->resErr('计划时间不能小于当前时间');
        $map = [
            'insurance_id' => $this->input_data['id'],
            'status' => ['<',20], // 状态在20以下，表示正在退保，或者已经退保
        ];
        if( db('InsuranceRefundPlan')->where($map)->find() ) $this->resErr('此保单已存在退保计划，无法重复提交');


        # 创建退保计划
        $data = [
            'insurance_id' => $this->input_data['id'],
            'plan_date' => $this->input_data['plan_date'],
            'remark' => $this->input_data['remark'],
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        $rId = db('InsuranceRefundPlan')->insertGetId($data);

        $this->resSuc('ok');
    }
    private function _updateInsuranceStatus($id)
    {
        # 查找相关保单
        $map = [
            'id' => $id
        ];
        $insurance = db('Insurance')->where($map)->find();

        $data = [
            'refund_amount' => formatMoneySave($this->input_data['refund_amount']),
            'refund_rebate' => formatMoneySave($this->input_data['refund_rebate']),
            'refund_date' => $this->input_data['refund_date'],
            'refund_pdf' => $this->input_data['refund_pdf'],

            'refund_time' => time(),
            'refund_user' => $this->user['realname'],
            'refund_user_id' => $this->user['id'],
        ];
        db('Insurance')->where($map)->update($data);

        # 更新车辆的保险到期时间
        $map = [
            'id' => $insurance['vehicle_id']
        ];

        $data = $insurance['cate'] == '交强险' ? ['insurance_date_c' => $this->input_data['refund_date']] : ['insurance_date_b' => $this->input_data['refund_date']];
        db('Vehicle')->where($map)->update($data);
    }

    // 完成退保，填完退保金额，返还返点，上传pdf，填写实际退保时间
    public function done()
    {
        # 创建退保记录
        $data = [
            'insurance_id' => $this->input_data['insurance_id'],
            'refund_to_driver' => 0,
            'refund_reason' => '',
            'refund_images' => '',
            'status' => 20,
            'done_user' => $this->user['realname'],
            'done_user_id' => $this->user['id'],
            'done_time' => time(),
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        $rId = db('InsuranceRefund')->insertGetId($data);


        # 更新计划状态
        $data = [
            'id' => $this->input_data['id'],
            'insurance_refund_id' => $rId,
            'status' => 20,
            'done_user' => $this->user['realname'],
            'done_user_id' => $this->user['id'],
            'done_time' => time(),
        ];
        db('InsuranceRefundPlan')->update($data);

        # 更新保单状态
        $this->_updateInsuranceStatus($this->input_data['insurance_id']);




        $this->resSuc('ok');
    }



    public function getById()
    {
        $map['id'] = $this->input_data['id'];
        $result = db('InsuranceRefundPlan')->where($map)->find();
        $this->resSuc($result);
    }

}
